package io.renren.modules.job.task.pdf;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.data.domain.Example;

import com.itextpdf.text.DocumentException;

import io.renren.modules.app.entity.Qj;
import io.renren.modules.app.entity.nosql.LcPdfTemplate;
import io.renren.modules.app.entity.nosql.PdfInfo;
import io.renren.modules.app.nosql.mongo.IPdfRepo;
import io.renren.modules.app.service.IQjService;
import io.renren.modules.app.utils.FkUtil;
import io.renren.modules.app.utils.GoFastdfs;
import io.renren.modules.app.utils.GoFastdfs.Result;
import io.renren.modules.job.task.TaskPdf;
import io.renren.modules.app.utils.PathUtil;
import io.renren.modules.app.utils.PdfUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class PdfQj implements IPdf {
	// 流程id
	private String idLiucheng;
	// 要生成pdf的路径
	private File pdf;
	private String process;
	private Map<String, Object> params;
	private IPdfRepo pdfRepo;
	private IQjService qjService;
	private LcPdfTemplate lcTemplate;

	@Override
	public void gen() throws IOException, DocumentException, com.lowagie.text.DocumentException {
		List<Qj> qjs = qjService.findQjByBPM_INST_HIS(idLiucheng);
		Qj qj = qjs.get(0);
		System.out.println(qj);

		params.put("qj", qj);
		
		String content = new FkUtil(params, lcTemplate).render();
		String picPath = "file:/" + PathUtil.getCurrentPath() + "/logo.png";

		if (new PdfUtil(pdf, picPath).createPdf(content)) {
			if (!pdfRepo.findOne(Example.of(new PdfInfo().setName(pdf.getName()))).isPresent()) {
				GoFastdfs goFastdfs = new GoFastdfs(TaskPdf.fileServer, "pdf", "pdf");
				Result upload = goFastdfs.upload(pdf);
				pdfRepo.save(new PdfInfo(pdf.getName(), process, upload.getPath()));
			}
		}
	}
}